/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  cleanUpFormItem
 *  CleanUpFormItem
 *  clean_up_form
 *  cleanUpForm
 */


/***** variables declartion section, begin *****/
var cleanUpFormItemInputMode = wacFormInputMode.add;
var cleanUpFormItemObj = {};
var cleanUpFormObj = {};

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        initCleanUpFormItemFormDialog();

        initCleanUpFormItemForm();

        bindCleanUpFormItemEvents();
    }
);

function bindCleanUpFormItemEvents()
{
    $("#cleanUpFormItemFormDialog").bind('dialogopen', function(event, ui)
    {
        initCleanUpFormItemFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.cleanUpFormItem.name);//
    });

    $("#cleanUpFormItemFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#cleanUpFormItem_btnSubmit").bind('click', function (e)
    {
        submitCleanUpFormItemForm();
    });

    $("#cleanUpFormItem_btnClose").bind('click', function (e)
    {
        $("#cleanUpFormItemFormDialog").dialog('close');
    });

    $("#cleanUpFormItem_goods_number, #cleanUpFormItem_goods_number_unit_price").bind('change', function (e)
    {
        $("#cleanUpFormItem_processing_fee").attr("value", Number($("#cleanUpFormItem_goods_number").val()) * Number($("#cleanUpFormItem_goods_number_unit_price").val()));
        $("#cleanUpFormItem_processing_fee").formatCurrency({symbol:"",digitGroupSymbol:"", roundToDecimalPlace:-1});
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t1052")
        {
            $("div[aria-labelledby='ui-dialog-title-cleanUpFormItemFormDialog']").remove();
            $("#cleanUpFormItemFormDialog").remove();
        }
    });
}


function initCleanUpFormItemFormDialog()
{
//    wacDebugLog("initCleanUpFormItemFormDialog.");
    $("#cleanUpFormItemFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 850,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initCleanUpFormItemForm()
{
    $("#cleanUpFormItemForm").validationEngine();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initCleanUpFormItemFormData()
{
    wacShowBlockUILoading("#cleanUpFormItemFormDialog");
    $('#cleanUpFormItem_color_id, #cleanUpFormItem_jar_id, #cleanUpFormItem_goods_category_id, #cleanUpFormItem_goods_number_unit_code').empty();

    var params = {
        "data_format" : 'json',
        "clean_up_form_id": cleanUpFormObj.id
    };

    $.ajax({
        url: BASE_URL + "cleanUpFormItem/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initCleanUpFormItemFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initCleanUpFormItemFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#cleanUpFormItem_goods_number_unit_code");
        }
   }

   setupCleanUpFormItemFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#cleanUpFormItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupCleanUpFormItemFormDefaultValues(defaultValueObj)
{
    $("#cleanUpFormItem_clean_up_form_id").attr("value", cleanUpFormObj.id);
    $("#cleanUpFormItem_clean_up_form_code").attr("innerHTML", cleanUpFormObj.code);
    $("#cleanUpFormItem_production_order_code").attr("innerHTML", cleanUpFormObj.production_order_code);
    $("#cleanUpFormItem_supplier_name").attr("innerHTML", cleanUpFormObj.supplier_name);
    $("#cleanUpFormItem_factory_name").attr("innerHTML", cleanUpFormObj.factory_name);

    if(cleanUpFormItemInputMode == wacFormInputMode.add)   // use default values
    {
        $("#cleanUpFormItem_id").attr("value", 0);
        $('#cleanUpFormItem_goods_category_id').flexbox(BASE_URL + 'factory/GetStockWeaveCategoryIdNameHashInFormat?data_format=jsonFlexbox&factory_id=' + cleanUpFormObj.supplier_id, {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#cleanUpFormItem_jar_id').flexbox(BASE_URL + 'jar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "jar_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#cleanUpFormItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#cleanUpFormItem_goods_number_unit_code option:[value='"+ cleanUpFormObj.goods_amount_unit_code +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#cleanUpFormItem_goods_category_id').flexbox(BASE_URL + 'factory/GetStockWeaveCategoryIdNameHashInFormat?data_format=jsonFlexbox&factory_id=' + cleanUpFormObj.supplier_id, {
            initialValue: cleanUpFormItemObj.goods_category_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpFormItem_goods_category_id_input').val(cleanUpFormItemObj.goods_category_name);

        $('#cleanUpFormItem_jar_id').flexbox(BASE_URL + 'jar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: cleanUpFormItemObj.jar_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "jar_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpFormItem_jar_id_input').val(cleanUpFormItemObj.jar_name);

        $('#cleanUpFormItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: cleanUpFormItemObj.color_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpFormItem_color_id_input').val(cleanUpFormItemObj.color_name);

//        $("#cleanUpFormItem_batch").attr("value", cleanUpFormItemObj.batch);
        $("#cleanUpFormItem_goods_number_unit_price").attr("value", cleanUpFormItemObj.goods_number_unit_price);
        $("#cleanUpFormItem_goods_number").attr("value", cleanUpFormItemObj.goods_number);
        $("#cleanUpFormItem_id").attr("value", cleanUpFormItemObj.id);

        $("#cleanUpFormItem_memo").attr("value", cleanUpFormItemObj.memo);

        $("#cleanUpFormItem_goods_number_unit_code option:[value='"+ cleanUpFormItemObj.goods_number_unit_code +"']").attr('selected', 'selected');
    }

//wacDebugLog($.dump(cleanUpFormItemObj));
//    wacDebugLog($.dump(cleanUpFormObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("cleanUpFormItemInputMode: " + cleanUpFormItemInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/

function cleanUpFormItemOpenModuleForm(moduleFormName, moduleName, inputMode, rowid, parentId)
{
    cleanUpFormItemInputMode = inputMode;

    if(parentId === undefined || parentId==0){
        cleanUpFormObj = {};
    }
    else
    {
        cleanUpFormObj = $("#cleanUpFormList").getRowData(parentId);
    }

    if(rowid === undefined || rowid==0){
        cleanUpFormItemObj = {};
    }
    else
    {
        cleanUpFormItemObj = $("#cleanUpFormList_" + cleanUpFormObj.id + "_t").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateCleanUpFormItemForm()
{
    var validateFlag = true;

    if (!$("#cleanUpFormItemForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    return validateFlag;
}

function submitCleanUpFormItemForm()
{
    if(!validateCleanUpFormItemForm()){
        return;
    }

    wacShowBlockUILoading("#cleanUpFormItemFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(cleanUpFormItemInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "cleanUpFormItem/add";
    }
    else{
        submitUrl = BASE_URL + "cleanUpFormItem/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#cleanUpFormItemForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitCleanUpFormItemFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitCleanUpFormItemFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#cleanUpFormList_" + cleanUpFormObj.id + "_t").trigger("reloadGrid");
   }

   wacHideBlockUI("#cleanUpFormItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/